/*
 * @Description: 部门管理接口
 * @Author: zhihong deng
 * @Date: 2021-09-20 13:12:36
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-09-20 16:07:57
 */
const router = require('koa-router')()
const util = require('../utils/util')
const Dept = require('../models/deptSchema')

router.prefix('/dept') // 路由前缀

// 部门树形列表
router.get('/list', async (ctx) => {
  let { deptName} = ctx.request.query
  let params = {}
  if (deptName) params.deptName = deptName
  let rootList = await Dept.find(params)
  if (deptName) {
    ctx.body = util.success(rootList)
  } else {
    let treeList = getTreeDept( rootList, null, [])
    ctx.body = util.success(treeList)
  }
})
// 递归拼接树形列表
function getTreeDept(rootList, id, list) {
  // 先遍历一级菜单
  for (let i = 0; i < rootList.length; i++) {
    let item = rootList[i]
    if (String(item.parentId.slice().pop()) == String(id)) {
      list.push(item._doc)
    }
  }
  // 在一级菜单中加入children
  list.map( item => {
    item.children = []
    getTreeDept(rootList, item._id, item.children)
    // 若果没有二级菜单就删掉children这个字段
    if(item.children.length == 0){
      delete item.children
    }
  })
  return list
}

// 部门创建/编辑/删除
router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info;
  try {
    if (action == 'create') {
      res = await Dept.create(params)
      info = "创建成功"
    }else if(action == 'edit'){
      params.updateTime = new Date()
      res = await Dept.findByIdAndUpdate(_id, params)
      info = "编辑成功"
    }else if (action == 'delete'){
			res = await Dept.findOneAndRemove(_id) // 先删除当前选中的节点
			// 如果删除的是父级，那父级id下的子级也被删除
			await Dept.deleteMany({ parentId: { $all: [_id] } })
      info = "删除成功"
    }
    ctx.body = util.success('', info)
  } catch (error) {
    ctx.body = util.fail(error.stack)
  }
})
module.exports = router